import React, { useState } from 'react';
import { 
  InboxOutlined, 
  UploadOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  FilePptOutlined,
  FilePdfOutlined,
  FileImageOutlined,
  FileTextOutlined,
  FileOutlined,
  DeleteOutlined,
  EyeOutlined,
  DownloadOutlined,
  CloseCircleFilled,
  CheckCircleFilled,
} from '@ant-design/icons';
import type { UploadProps, UploadFile } from 'antd';
import { Upload, Button, Space, message, Divider, Typography, Row, Col, Tag, Tooltip } from 'antd';
import { createStyles } from 'antd-style';

const { Dragger } = Upload;
const { Text, Title } = Typography;

// 样式定义
const useStyles = createStyles(({ token, css }) => ({
  fileItem: css`
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border: 1px solid ${token.colorBorderSecondary};
    border-radius: ${token.borderRadius}px;
    margin-bottom: 8px;
    background: ${token.colorBgContainer};
    transition: all 0.3s ease;
    
    &:hover {
      background: ${token.colorBgTextHover};
      border-color: ${token.colorPrimary};
      
      .file-actions {
        opacity: 1;
      }
    }
  `,
  fileIcon: css`
    font-size: 32px;
    margin-right: 12px;
    flex-shrink: 0;
  `,
  fileInfo: css`
    flex: 1;
    min-width: 0;
  `,
  fileName: css`
    font-size: 14px;
    font-weight: 500;
    color: ${token.colorText};
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  `,
  fileMeta: css`
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 12px;
    color: ${token.colorTextSecondary};
  `,
  fileActions: css`
    display: flex;
    gap: 8px;
    opacity: 0;
    transition: opacity 0.3s ease;
  `,
  actionBtn: css`
    color: ${token.colorTextSecondary};
    cursor: pointer;
    transition: color 0.3s ease;
    
    &:hover {
      color: ${token.colorPrimary};
    }
  `,
  errorItem: css`
    border-color: ${token.colorError};
  `,
}));

// 时间格式化函数
const formatTime = (date: Date): string => {
  const now = new Date();
  const diffInMs = now.getTime() - date.getTime();
  const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));
  
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const timeStr = `${hours}:${minutes}`;
  
  // 今天
  if (diffInDays === 0) {
    return timeStr;
  }
  
  // 昨天
  if (diffInDays === 1) {
    return `昨天 ${timeStr}`;
  }
  
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const currentYear = now.getFullYear();
  const fileYear = date.getFullYear();
  
  // 今年之内
  if (fileYear === currentYear) {
    return `${month}-${day} ${timeStr}`;
  }
  
  // 非今年
  return `${fileYear}-${month}-${day} ${timeStr}`;
};

// 获取文件大小格式化
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
};

// 根据文件扩展名获取图标
const getFileIcon = (fileName: string) => {
  const ext = fileName.split('.').pop()?.toLowerCase() || '';
  const iconStyle = { fontSize: 32 };
  
  // 文档类型
  if (['doc', 'docx', 'dot', 'dotx'].includes(ext)) {
    return <FileWordOutlined style={{ ...iconStyle, color: '#2b579a' }} />;
  }
  
  // 表格类型
  if (['xls', 'xlsx', 'xlsm', 'csv'].includes(ext)) {
    return <FileExcelOutlined style={{ ...iconStyle, color: '#217346' }} />;
  }
  
  // PPT类型
  if (['ppt', 'pptx', 'pps', 'ppsx', 'pot'].includes(ext)) {
    return <FilePptOutlined style={{ ...iconStyle, color: '#d24726' }} />;
  }
  
  // PDF类型
  if (ext === 'pdf') {
    return <FilePdfOutlined style={{ ...iconStyle, color: '#f40f02' }} />;
  }
  
  // 图片类型
  if (['png', 'jpg', 'jpeg', 'gif', 'ico', 'bmp', 'svg', 'webp'].includes(ext)) {
    return <FileImageOutlined style={{ ...iconStyle, color: '#52c41a' }} />;
  }
  
  // 文本类型
  if (['txt', 'md'].includes(ext)) {
    return <FileTextOutlined style={{ ...iconStyle, color: '#8c8c8c' }} />;
  }
  
  // 编程文件
  if (['c', 'cpp', 'java', 'py', 'js', 'ts', 'tsx', 'jsx', 'json', 'xml', 'html', 'css'].includes(ext)) {
    return <FileTextOutlined style={{ ...iconStyle, color: '#1890ff' }} />;
  }
  
  // 默认
  return <FileOutlined style={{ ...iconStyle, color: '#8c8c8c' }} />;
};

// 自定义文件列表渲染
interface CustomUploadFile extends UploadFile {
  size?: number;
  uploader?: string;
  uploadTime?: Date;
  hasWPSSupport?: boolean;
}

const App: React.FC = () => {
  const { styles, cx } = useStyles();
  const [fileList1, setFileList1] = useState<CustomUploadFile[]>([]);
  const [fileList2, setFileList2] = useState<CustomUploadFile[]>([
    {
      uid: '-1',
      name: '快速了解需求文档.doc',
      status: 'done',
      size: 32.4 * 1024 * 1024, // 32.4M
      uploader: '张自研',
      uploadTime: new Date(2024, 10, 4, 2, 35),
      hasWPSSupport: true,
    },
    {
      uid: '-2',
      name: '快速了解需求文档',
      status: 'done',
      size: 32.4 * 1024 * 1024,
      uploader: '张自研',
      uploadTime: new Date(2024, 10, 4, 2, 35),
    },
    {
      uid: '-3',
      name: '快速了解需求文档 | Quickly understand.ppt',
      status: 'done',
      size: 32.4 * 1024 * 1024,
      uploader: '张自研',
      uploadTime: new Date(2024, 10, 4, 2, 35),
      hasWPSSupport: true,
    },
    {
      uid: '-4',
      name: '快速了解需求文档 | Quickly...',
      status: 'uploading',
      percent: 45,
      size: 32.4 * 1024 * 1024,
      uploader: '张自研',
      uploadTime: new Date(),
    },
    {
      uid: '-5',
      name: '快速了解需求文档.pdf',
      status: 'error',
      size: 32.4 * 1024 * 1024,
      uploader: '张自研',
      uploadTime: new Date(),
    },
  ]);

  // 自定义文件项渲染
  const renderCustomFileItem = (file: CustomUploadFile) => {
    const isError = file.status === 'error';
    const isUploading = file.status === 'uploading';
    
    return (
      <div className={cx(styles.fileItem, isError && styles.errorItem)} key={file.uid}>
        {/* 文件图标 */}
        <div className={styles.fileIcon}>
          {getFileIcon(file.name)}
        </div>
        
        {/* 文件信息 */}
        <div className={styles.fileInfo}>
          <div className={styles.fileName}>
            {file.name}
          </div>
          <div className={styles.fileMeta}>
            {file.size && <span>{formatFileSize(file.size)}</span>}
            {file.uploader && <span>来自 {file.uploader}</span>}
            {file.uploadTime && <span>{formatTime(file.uploadTime)}</span>}
            {file.hasWPSSupport && (
              <Tag color="blue" style={{ margin: 0 }}>WPS支持</Tag>
            )}
            {isError && (
              <span style={{ color: '#ff4d4f' }}>
                <CloseCircleFilled style={{ marginRight: 4 }} />
                上传失败
              </span>
            )}
            {isUploading && file.percent && (
              <span style={{ color: '#1890ff' }}>上传中 {file.percent}%</span>
            )}
          </div>
        </div>
        
        {/* 操作按钮 */}
        <div className={cx(styles.fileActions, 'file-actions')}>
          <Tooltip title="预览">
            <EyeOutlined 
              className={styles.actionBtn} 
              onClick={() => message.info(`预览 ${file.name}`)}
            />
          </Tooltip>
          <Tooltip title="下载">
            <DownloadOutlined 
              className={styles.actionBtn}
              onClick={() => message.info(`下载 ${file.name}`)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <DeleteOutlined 
              className={styles.actionBtn}
              onClick={() => {
                setFileList2(fileList2.filter(f => f.uid !== file.uid));
                message.success('删除成功');
              }}
            />
          </Tooltip>
        </div>
      </div>
    );
  };

  const draggerProps: UploadProps = {
    name: 'file',
    multiple: true,
    fileList: fileList1,
    accept: '.doc,.docx,.dot,.dotx,.xls,.xlsx,.xlsm,.csv,.ppt,.pptx,.pps,.ppsx,.pot,.pdf,.png,.jpg,.jpeg,.gif,.ico,.bmp,.svg,.webp,.txt,.md,.c,.cpp,.java,.py,.js,.ts,.tsx,.jsx,.json,.xml,.html,.css',
    action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
    onChange(info) {
      const { status } = info.file;
      let newFileList = [...info.fileList].map(file => ({
        ...file,
        size: file.size || Math.random() * 50 * 1024 * 1024,
        uploader: '张自研',
        uploadTime: new Date(),
      })) as CustomUploadFile[];
      
      newFileList = newFileList.slice(-10);
      setFileList1(newFileList);

      if (status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onDrop(e) {
      console.log('拖放的文件', e.dataTransfer.files);
    },
  };

  const simpleProps: UploadProps = {
    name: 'file',
    fileList: fileList2,
    accept: '.doc,.docx,.dot,.dotx,.xls,.xlsx,.xlsm,.csv,.ppt,.pptx,.pps,.ppsx,.pot,.pdf,.png,.jpg,.jpeg,.gif,.ico,.bmp,.svg,.webp,.txt,.md',
    action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
    showUploadList: false,
    onChange(info) {
      let newFileList = [...info.fileList].map(file => ({
        ...file,
        size: file.size || Math.random() * 50 * 1024 * 1024,
        uploader: '张自研',
        uploadTime: new Date(),
      })) as CustomUploadFile[];
      
      setFileList2(newFileList);
      
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };

  return (
    <Space direction="vertical" size="large" style={{ width: '100%' }}>
      <div>
        <Title level={5}>● 文档上传</Title>
        <Text type="secondary">1. 空状态拖拽上传：将文件拖拽至虚框内上传</Text>
        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={12}>
            <Dragger {...draggerProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined style={{ fontSize: 48, color: '#1890ff' }} />
              </p>
              <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
              <p className="ant-upload-hint">
                支持扩展名：.doc .docx .xls .xlsx .ppt .pptx .pdf .jpg .png...
              </p>
            </Dragger>
          </Col>
        </Row>
      </div>

      <Divider />

      <div>
        <Text type="secondary">2. 极简模式：用于卡片详情内的文档上传操作</Text>
        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={12}>
            <Upload {...simpleProps}>
              <Button icon={<UploadOutlined />}>上传</Button>
            </Upload>
            <div style={{ marginTop: 8 }}>
              <Text type="secondary" style={{ fontSize: 12 }}>
                注意文档上传的间距示范式；
              </Text>
            </div>
          </Col>
          <Col span={12}>
            <Button icon={<UploadOutlined />}>关联</Button>
            <div style={{ marginTop: 8 }}>
              <Text type="secondary" style={{ fontSize: 12 }}>
                内容居版权提示页和排版格式连店
              </Text>
            </div>
          </Col>
        </Row>
      </div>

      <Divider />

      <div>
        <Title level={5}>内容标题</Title>
        <Space direction="vertical" size="middle" style={{ width: '100%', marginTop: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text>共 {fileList2.length} 条</Text>
            <Space>
              <Upload {...simpleProps}>
                <Button icon={<UploadOutlined />}>上传</Button>
              </Upload>
              <Button>关联</Button>
            </Space>
          </div>
          
          {/* 自定义文件列表 */}
          <div>
            {fileList2.map(file => renderCustomFileItem(file as CustomUploadFile))}
          </div>
          
          {/* 展开查看更多 */}
          {fileList2.length > 4 && (
            <div style={{ textAlign: 'center', marginTop: 8 }}>
              <Button type="link">展开查看 4 项</Button>
            </div>
          )}
        </Space>
      </div>

      <Divider />

      <div>
        <Title level={5}>绝对时间</Title>
        <Text type="secondary">
          针对时间精确度要求较高的用户，强调信息发布的精确时间点，有回顾过去内容并通过绝对时间用索检索信息的诉求。
        </Text>
        <div style={{ marginTop: 16, padding: 16, background: '#fafafa', borderRadius: 8 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <div><Text strong>时间格式规范：</Text></div>
            <div><Text type="secondary">• 今天：hh:mm（02:35）</Text></div>
            <div><Text type="secondary">• 昨天：昨天 hh:mm（昨天 02:35）</Text></div>
            <div><Text type="secondary">• 昨天之前、今年之内：mm-dd hh:mm（09-17 02:35）</Text></div>
            <div><Text type="secondary">• 非今年内：yyyy-mm-dd hh:mm（2019-09-17 02:35）</Text></div>
          </Space>
        </div>
      </div>

      <Divider />

      <div>
        <Title level={5}>注意文档支持格式区分</Title>
        <div style={{ marginTop: 16, padding: 16, background: '#fafafa', borderRadius: 8 }}>
          <Row gutter={[16, 16]}>
            <Col span={12}>
              <div>
                <Text strong>文档类型：</Text>
                <div style={{ marginTop: 8 }}>
                  <Space wrap>
                    <FileWordOutlined style={{ fontSize: 24, color: '#2b579a' }} />
                    <Text type="secondary">.doc, .docx, .dot, .dotx</Text>
                  </Space>
                </div>
              </div>
            </Col>
            <Col span={12}>
              <div>
                <Text strong>表格类型：</Text>
                <div style={{ marginTop: 8 }}>
                  <Space wrap>
                    <FileExcelOutlined style={{ fontSize: 24, color: '#217346' }} />
                    <Text type="secondary">.xls, .xlsx, .xlsm, .csv</Text>
                  </Space>
                </div>
              </div>
            </Col>
            <Col span={12}>
              <div>
                <Text strong>PPT类型：</Text>
                <div style={{ marginTop: 8 }}>
                  <Space wrap>
                    <FilePptOutlined style={{ fontSize: 24, color: '#d24726' }} />
                    <Text type="secondary">.ppt, .pptx, .pps, .ppsx, .pot</Text>
                  </Space>
                </div>
              </div>
            </Col>
            <Col span={12}>
              <div>
                <Text strong>图片类型：</Text>
                <div style={{ marginTop: 8 }}>
                  <Space wrap>
                    <FileImageOutlined style={{ fontSize: 24, color: '#52c41a' }} />
                    <Text type="secondary">.png, .jpg, .jpeg, .gif, .ico, .bmp, .svg, .webp</Text>
                  </Space>
                </div>
              </div>
            </Col>
            <Col span={12}>
              <div>
                <Text strong>PDF类型：</Text>
                <div style={{ marginTop: 8 }}>
                  <Space wrap>
                    <FilePdfOutlined style={{ fontSize: 24, color: '#f40f02' }} />
                    <Text type="secondary">.pdf</Text>
                  </Space>
                </div>
              </div>
            </Col>
            <Col span={12}>
              <div>
                <Text strong>文本类型：</Text>
                <div style={{ marginTop: 8 }}>
                  <Space wrap>
                    <FileTextOutlined style={{ fontSize: 24, color: '#8c8c8c' }} />
                    <Text type="secondary">.txt, .md</Text>
                  </Space>
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </div>
    </Space>
  );
};

export default App;

